<template>
  <view class="myInfo-container">
    <view class="page-header">
      <view class="header-title">个人信息</view>
      <view class="header-subtitle">请完善您的个人资料</view>
    </view>

    <view class="form-container">
      <uni-forms
        ref="form"
        :modelValue="formData"
        :rules="rules"
        label-position="left"
        input-align="right"
      >
        <view class="form-section">
          <view class="section-title">基本信息</view>

          <uni-forms-item
            required
            label="姓名"
            name="realName"
            class="form-item-half"
          >
            <input
              class="form-input"
              focus
              v-model="formData.realName"
              placeholder="请输入姓名"
            />
          </uni-forms-item>

          <uni-forms-item
            required
            label="性别"
            name="gender"
            class="form-item-half"
          >
            <view class="radio-group-container">
              <radio-group
                name="gender"
                class="radio-group"
                @change="changeGender"
              >
                <label
                  class="radio-item"
                  :class="{ checked: selected === '1' }"
                >
                  <radio
                    value="1"
                    :checked="selected === '1'"
                    color="#2cbaff"
                  />
                  <text class="radio-text">男</text>
                </label>
                <label
                  class="radio-item"
                  :class="{ checked: selected === '0' }"
                >
                  <radio
                    value="0"
                    :checked="selected === '0'"
                    color="#2cbaff"
                  />
                  <text class="radio-text">女</text>
                </label>
              </radio-group>
            </view>
          </uni-forms-item>
          <uni-forms-item
            required
            label="民族"
            name="nationality"
            class="form-item-half"
          >
            <input
              class="form-input"
              v-model="formData.nationality"
              placeholder="请输入民族"
            />
          </uni-forms-item>

          <uni-forms-item
            required
            label="身份证号"
            name="idNo"
            class="form-item-half"
          >
            <input
              class="form-input"
              type="idcard"
              v-model="formData.idNo"
              placeholder="请输入身份证号"
            />
          </uni-forms-item>
        </view>

        <view class="form-section">
          <view class="section-title">联系方式</view>

          <uni-forms-item
            required
            label="住址"
            name="homeAddr"
            class="form-item-row"
          >
            <input
              class="form-input"
              v-model="formData.homeAddr"
              auto-height
              placeholder="请输入住址"
            />
          </uni-forms-item>

          <uni-forms-item
            required
            label="手机号"
            name="mobile"
            class="form-item-half"
          >
            <input
              class="form-input"
              type="tel"
              v-model="formData.mobile"
              placeholder="请输入手机号"
            />
          </uni-forms-item>

          <uni-forms-item
            required
            label="电子邮箱"
            name="email"
            class="form-item-half"
          >
            <input
              class="form-input"
              type="text"
              v-model="formData.email"
              placeholder="请输入电子邮箱"
            />
          </uni-forms-item>
        </view>

        <view class="form-section">
          <view class="section-title">证件上传</view>

          <uni-forms-item
            required
            label="身份证正面"
            :label-width="100"
            name="idCardFront"
            class="form-item-upload"
          >
            <uni-file-picker
              v-model="zhengArr"
              limit="1"
              file-mediatype="image"
              @select="onSelect"
              :image-styles="filePickerStyles"
            >
              <view class="file-picker-button">
                <view class="upload-icon">+</view>
                <text class="upload-text">上传正面照片</text>
              </view>
            </uni-file-picker>
          </uni-forms-item>

          <uni-forms-item
            required
            label="身份证反面"
            :label-width="100"
            name="idCardBack"
            class="form-item-upload"
          >
            <uni-file-picker
              v-model="fanArr"
              limit="1"
              file-mediatype="image"
              @select="onSelectBack"
              :image-styles="filePickerStyles"
            >
              <view class="file-picker-button">
                <view class="upload-icon">+</view>
                <text class="upload-text">上传反面照片</text>
              </view>
            </uni-file-picker>
          </uni-forms-item>

          <uni-forms-item
            required
            label="无犯罪记录"
            :label-width="100"
            name="noCriminal"
            class="form-item-upload"
          >
            <uni-file-picker
              v-model="noCrmArr"
              limit="1"
              file-mediatype="image"
              @select="onNoCriminal"
              :image-styles="filePickerStyles"
            >
              <view class="file-picker-button">
                <view class="upload-icon">+</view>
                <text class="upload-text">上传证明</text>
              </view>
            </uni-file-picker>
          </uni-forms-item>

          <uni-forms-item
            required
			label="一寸照片"
            :label-width="100"
            name="headImg"
            class="form-item-upload"
          >
            <uni-file-picker
              v-model="photoArr"
              limit="1"
              file-mediatype="image"
              @select="onPhoto"
              :image-styles="filePickerStyles"
            >
              <view class="file-picker-button">
                <view class="upload-icon">+</view>
                <text class="upload-text">上传照片</text>
              </view>
            </uni-file-picker>
          </uni-forms-item>
        </view>
      </uni-forms>

      <button class="submit-button" @click="submit" type="primary">
        保存信息
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { onLoad, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { toPlainObject, checkFn, uploadImg, globalData } from "@/utils/util";
import api from "@/utils/api.js";

let zhengArr = reactive([]);
let fanArr = reactive([]);
let sfzArr = ["", ""];
let noCrmArr = reactive([]);
let photoArr = reactive([]);

const courseId = ref(""); // 课程id
const organId = ref(""); // 机构id
const form = ref(null);
let selected = ref("0");
let formData = reactive({
  realName: "",
  gender: "0",
  nationality: "",
  idNo: "",
  homeAddr: "",
  mobile: "",
  email: "",
  noCriminal: "",
  headImg: "",
});

const filePickerStyles = reactive({
  width: 220, // 宽度
  height: 160, // 高度
  border: {
    color: "#f2f2f2",
    width: 1,
    style: "solid",
    radius: "8rpx",
  },
});

// 上传身份证正面
const onSelect = async (e) => {
  const file = e.tempFiles[0];
  await uploadImg(file).then((result) => {
    sfzArr[0] = result;
  });
};
// 上传身份证反面
const onSelectBack = async (e) => {
  const file = e.tempFiles[0];
  await uploadImg(file).then((result) => {
    sfzArr[1] = result;
  });
};
// 上传无犯罪记录证明
const onNoCriminal = async (e) => {
  const file = e.tempFiles[0];
  await uploadImg(file).then((result) => {
    formData.noCriminal = result;
  });
};
// 上传一英寸白底照片
const onPhoto = async (e) => {
  const file = e.tempFiles[0];
  await uploadImg(file).then((result) => {
    formData.headImg = result;
  });
};
// 选择性别
const changeGender = (e) => {
  selected.value = e.detail.value;
  formData.gender = e.detail.value;
};
const rules = ref({
  realName: {
    rules: [{ required: true, errorMessage: "姓名不能为空" }],
  },
  nationality: {
    rules: [
      { required: true, errorMessage: "民族不能为空" },
      { pattern: checkFn("nationality"), errorMessage: "民族格式不正确" },
    ],
  },
  idNo: {
    rules: [
      { required: true, errorMessage: "身份证号不能为空" },
      { pattern: checkFn("idNo"), errorMessage: "身份证号格式不正确" },
    ],
  },
  homeAddr: {
    rules: [{ required: true, errorMessage: "住址不能为空" }],
  },
  mobile: {
    rules: [
      { required: true, errorMessage: "手机号不能为空" },
      { pattern: checkFn("mobile"), errorMessage: "手机号格式不正确" },
    ],
  },
  email: {
    rules: [
      { required: true, errorMessage: "邮箱不能为空" },
      { format: "email", errorMessage: "邮箱格式不正确" },
    ],
  },
});
const submit = async () => {
  try {
    // 校验表单
    await form.value.validate();
    let userInfo = uni.getStorageSync("userInfo");
    formData = Object.assign(userInfo || {}, formData, {
      idImgs: `${sfzArr[0]},${sfzArr[1]}`,
    });
    uni.setStorageSync("userInfo", formData);
    await api.myInfoUpdate(formData).then((result) => {
      uni.showToast({
        title: "提交成功",
        icon: "success",
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    });
  } catch (error) {
    console.log("表单校验失败:", error);
  }
};
onLoad((options) => {
  courseId.value = options.courseId;
  organId.value = options.organId;

  Object.assign(formData, uni.getStorageSync("userInfo"));
  selected.value = formData.gender?.toString();
  if (formData.idImgs) {
    let arr = formData.idImgs.split(",");
    zhengArr = [{ url: globalData.OSS_URL + arr[0] }];
    sfzArr = arr;
    fanArr = [{ url: globalData.OSS_URL + arr[1] }];
  }
  if (formData.noCriminal)
    noCrmArr = [{ url: globalData.OSS_URL + formData.noCriminal }];
  if (formData.headImg)
    photoArr = [{ url: globalData.OSS_URL + formData.headImg }];
});

// 分享给朋友
onShareAppMessage(() => {
  return {
    title: '个人信息 - 飞手之家',
    path: '/pages/myInfo/myInfo',
    imageUrl: '/static/images/head.jpg'
  };
});

// 分享到朋友圈
onShareTimeline(() => {
  return {
    title: '个人信息 - 飞手之家',
    query: '',
    imageUrl: '/static/images/head.jpg'
  };
});
</script>

<style lang="scss" scoped>
.myInfo-container {
  background-color: #f6f8fa;
  min-height: 100vh;
  padding-bottom: 40rpx;
}

.page-header {
  background-color: #2cbaff;
  padding: 40rpx 40rpx 60rpx;
  color: #fff;
  position: relative;
  margin-bottom: 30rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.header-subtitle {
  font-size: 26rpx;
  opacity: 0.9;
}

.form-container {
  width: 92%;
  margin: 0 auto;
  position: relative;
  top: -40rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

// 半宽表单项
.form-item-half {
  flex: 0 0 calc(50% - 20rpx);
  margin: 0 10rpx;

  // 修复标签换行和输入框右对齐问题
  :deep(.uni-forms-item__inner) {
    flex-direction: row;
    align-items: center;
  }

  :deep(.uni-forms-item__label) {
    width: 120rpx;
    justify-content: flex-start;
    padding-right: 12rpx;
    white-space: nowrap;
  }

  :deep(.uni-forms-item__content) {
    flex: 1;
  }
}

// 上传组件表单项
.form-item-upload {
  flex: 0 0 calc(50% - 20rpx);
  margin: 0 10rpx;
  
  :deep(.uni-forms-item__inner) {
    flex-direction: column;
    align-items: flex-start;
  }
  
  :deep(.uni-forms-item__label) {
    width: auto;
    padding-bottom: 16rpx;
    white-space: nowrap;
  }
  
  :deep(.uni-forms-item__content) {
    width: 100%;
  }
}

// 调整上传行的样式
.upload-row {
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  position: relative;
  padding-left: 24rpx;

  &::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 8rpx;
    height: 32rpx;
    background-color: #2cbaff;
    border-radius: 4rpx;
  }
}

.form-input {
  height: 80rpx;
  border-bottom: 1px solid #eaeaea;
  font-size: 28rpx;
  color: #333;
  width: 100%;
}

.radio-group-container {
  padding: 20rpx 0;
}

.radio-group {
  display: flex;
  align-items: center;
}

.radio-item {
  display: flex;
  align-items: center;
  margin-right: 60rpx;

  &.checked {
    color: #2cbaff;
  }
}

.radio-text {
  margin-left: 8rpx;
  font-size: 28rpx;
}

.file-picker-button {
  width: 100%;
  height: 200rpx;
  background-color: #f9f9f9;
  border: 2rpx dashed #ddd;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #2cbaff;
  transition: all 0.3s;
  
  &:active {
    background-color: #edf8ff;
  }
}

.upload-icon {
  font-size: 50rpx;
  margin-bottom: 10rpx;
  color: #2cbaff;
}

.upload-text {
  font-size: 28rpx;
  color: #2cbaff;
  text-align: center;
}

.submit-button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #2cbaff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  margin-top: 40rpx;
  margin-bottom: 60rpx;
  box-shadow: 0 6rpx 20rpx rgba(44, 186, 255, 0.3);
}

:deep(.uni-forms-item__inner) {
  padding-bottom: 24rpx;
}

// 调整邮箱等长标签的宽度
:deep(.uni-forms-item__label) {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 0;
  min-width: 150rpx;

  .is-required {
    color: #ff5a5f;
  }
}

:deep(.uni-file-picker__container) {
  display: inline-block;
}

// 行显示的表单项（如住址）
.form-item-row {
  :deep(.uni-forms-item__inner) {
    flex-direction: row;
    align-items: center;
  }

  :deep(.uni-forms-item__label) {
    width: 120rpx;
    justify-content: flex-start;
    padding-right: 12rpx;
    white-space: nowrap;
  }

  :deep(.uni-forms-item__content) {
    flex: 1;
  }
}
</style>
